package com.tencreat.service.mall.impl;

import cn.hutool.json.JSONConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.entity.SysDept;
import com.tencreat.common.core.domain.entity.SysUser;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.common.utils.StringUtils;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.common.utils.http.HttpUtils;
import com.tencreat.domain.account.MallStore;
import com.tencreat.domain.account.MallSupplier;
import com.tencreat.domain.mall.*;
import com.tencreat.domain.mall.dto.MallGoodsAuditDTO;
import com.tencreat.domain.mall.dto.MallGoodsAddDTO;
import com.tencreat.domain.mall.dto.MallGoodsSearchDTO;
import com.tencreat.domain.mall.vo.*;
import com.tencreat.domain.mall.dto.*;
import com.tencreat.mapper.mall.MallGoodsMapper;
import com.tencreat.service.account.IMallStoreService;
import com.tencreat.service.account.IMallSupplierService;
import com.tencreat.service.mall.*;
import com.tencreat.service.system.ISysDeptService;
import com.tencreat.service.system.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商城商品基本信息Service业务层处理
 *
 * @author tencreat
 * @date 2021-08-13
 */
@Service
@Slf4j
public class MallGoodsServiceImpl extends ServiceImpl<MallGoodsMapper, MallGoods> implements IMallGoodsService {
    protected final Logger logger = LoggerFactory.getLogger("sys-orderGoods");

    private final IMallCategoryService mallCategoryService;//类目
    private final IMallCollectService mallCollectService;//收藏
    private final IMallCommentService mallCommentService;//评论
    private final IMallOrderGoodsService mallOrderGoodsService;//订单商品
    private final ISysDeptService sysDeptService;//部门管理

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IMallGoodsNormsService mallGoodsNormsService;//商品规格参数

    @Autowired
    private IMallStoreService mallStoreService;
    @Autowired
    private IMallSupplierService supplierService;//供应商


    @Autowired
    private IMallStoreSetmealService mallStoreSetmealService;


    public MallGoodsServiceImpl(IMallCategoryService mallCategoryService, IMallCollectService mallCollectService, IMallCommentService mallCommentService, IMallOrderGoodsService mallOrderGoodsService, ISysDeptService sysDeptService) {
        this.mallCategoryService = mallCategoryService;
        this.mallCollectService = mallCollectService;
        this.mallCommentService = mallCommentService;
        this.mallOrderGoodsService = mallOrderGoodsService;
        this.sysDeptService = sysDeptService;
    }


    /**
     * 查询商品基本信息
     *
     * @param id 商品基本信息ID
     * @return 商品基本信息
     */
    @Override
    public MallGoods selectMallGoodsById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    /**
     * 查询商品基本信息列表
     *
     * @param mallGoods 商品基本信息
     * @return 商品基本信息
     */
    @Override
    public List<MallGoods> selectMallGoodsList(MallGoods mallGoods) {
        return baseMapper.selectList(Wrappers.query(mallGoods));
    }

    /**
     * 新增商品基本信息
     *
     * @param mallGoods 商品基本信息
     * @return 结果
     */
    @Override
    public int insertMallGoods(MallGoods mallGoods) {
        mallGoods.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(mallGoods);
    }

    /**
     * 修改商品基本信息
     *
     * @param mallGoods 商品基本信息
     * @return 结果
     */
    @Override
    public int updateMallGoods(MallGoods mallGoods) {
        mallGoods.setUpdateTime(LocalDateTime.now());
        if (mallGoods.getIsOnSale() != null && mallGoods.getIsOnSale() == 1) {
            mallGoods.setShelfTime(LocalDateTime.now());
        }
        return baseMapper.updateById(mallGoods);
    }

    /**
     * 批量删除商品基本信息
     *
     * @param ids 需要删除的商品基本信息ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMallGoodsByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除商品基本信息信息
     *
     * @param id 商品基本信息ID
     * @return 结果
     */
    @Override
    public int deleteMallGoodsById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertMallGoodsPo(MallGoodsAddDTO mallGoodsAddVO) {
        //  新增时 在good中的价格设置为所有规格的最低价
        BigDecimal miniPrice = null;
        BigDecimal inventory = BigDecimal.ZERO;
        MallGoods goods = mallGoodsAddVO.getGoods();
        goods.setGoodsSn(TenCreatUtil.getOrderNo());
        if (goods != null) {
            if (mallGoodsAddVO.getNorms() == null || mallGoodsAddVO.getNorms().size() < 0) {
                throw new CustomException("规格信息不能为空");
            }
            goods.setCreateTime(LocalDateTime.now());
            goods.setPicUrl(JSONObject.parseObject(goods.getGallery(), ArrayList.class).get(0).toString());
            goods.setAuditStatus(1);
            goods.setGoodsType("1");
            goods.setOrderType("1");
            goods.setStore(0L);
            goods.setChain(0);
            goods.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            baseMapper.insert(goods);

            List<MallGoodsNorms> norms = mallGoodsAddVO.getNorms();
            for (MallGoodsNorms goodsNorms : norms) {
                inventory = inventory.add(BigDecimal.valueOf(goodsNorms.getInventory()));
                if (miniPrice == null) {
                    miniPrice = goodsNorms.getRetailPrice();
                    goods.setSupplyPrice(goodsNorms.getSupplyPrice());
                    goods.setDeductPrice(goodsNorms.getDeductPrice());
                }
                if (miniPrice.compareTo(goodsNorms.getRetailPrice()) > 0) {
                    miniPrice = goodsNorms.getRetailPrice();
                    goods.setSupplyPrice(goodsNorms.getSupplyPrice());
                    goods.setDeductPrice(goodsNorms.getDeductPrice());
                }
                goodsNorms.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
                goodsNorms.setGoodsId(goods.getId());
            }
            mallGoodsNormsService.saveOrUpdateBatch(norms);
        }
        goods.setInventory(inventory.longValue());
//        goods.setRetailPrice(miniPrice);
        goods.setRetailPrice(miniPrice);
        baseMapper.updateById(goods);
        return 1;
    }

    @Override
    public MallGoodsAllVO getInfoGoodsVo(ReqIdParam id) {
        MallGoodsAllVO mallGoodsAllVO = new MallGoodsAllVO();
        MallGoods goods = baseMapper.selectById(id.getId());
        MallGoodsDTO mallGoodsVO = new MallGoodsDTO();
        if (goods != null) {
            if (StringUtils.isNotEmpty(goods.getChainId())) {
                goods = supplierChainGoods(goods);
            }
            LambdaQueryChainWrapper<MallCategory> mallCategoryLambda = mallCategoryService.lambdaQuery();
            mallCategoryLambda.eq(MallCategory::getId, goods.getCategoryId());
            MallCategory child = mallCategoryLambda.one();
            mallCategoryLambda = mallCategoryService.lambdaQuery();
            mallCategoryLambda.eq(MallCategory::getId, child.getPid());
            MallCategory parent = mallCategoryLambda.one();
//            MallCategory one = mallCategoryLambda.eq(MallCategory::getId, child.getPid()).one();
            BeanUtils.copyProperties(goods, mallGoodsVO);
            if (goods.getSetmealId() != 0L) {
                MallStoreSetmeal storeSetmeal = mallStoreSetmealService.lambdaQuery().eq(MallStoreSetmeal::getId, goods.getSetmealId()).one();
                if (storeSetmeal != null) {
                    mallGoodsVO.setSetmeal(storeSetmeal.getName());
                }
            }
            if (goods.getChain() != null) {
                mallGoodsVO.setChain(Long.valueOf(goods.getChain()));
            }
            mallGoodsVO.setCategoryId(Arrays.asList(parent.getId(), child.getId()));
        }
        mallGoodsAllVO.setMallGoodsVO(mallGoodsVO);

        return mallGoodsAllVO;
    }


    @Override
    public IPage<MallGoodTableVO> pageTableVo(MallGoodsDTO goods) {
        MallGoods mallGoods = new MallGoods();
        BeanUtils.copyProperties(goods, mallGoods);
        IPage<MallGoods> page = new Page<>(mallGoods.getPageNum(), mallGoods.getPageSize());
        QueryWrapper<MallGoods> query = null;
        mallGoods.setName(null);
//        if (StringUtils.isNotEmpty(goods.getUserName())) {
//            SysUser sysUser = sysUserService.selectByNickName(goods.getUserName());
//            if (sysUser == null) {
//                return new Page<>(mallGoods.getPageNum(), mallGoods.getPageSize());
//            }
//            mallGoods.setUserId(sysUser.getUserId());
//        }
        //根据供应商名字模糊查询
        if (StringUtils.isNotEmpty(goods.getUserName())) {
            List<MallSupplier> mallSupplier = supplierService.selectByUserName(goods.getUserName());
            if (mallSupplier == null) {
                return new Page<>(mallGoods.getPageNum(), mallGoods.getPageSize());
            }
            ArrayList<Long> supplierIds = new ArrayList<>();
            ArrayList<Long> userIds = new ArrayList<>();

            for (MallSupplier supplier : mallSupplier) {
                supplierIds.add(supplier.getId());
                userIds.add(supplier.getUserId());

            }
            goods.setSupplierIds(supplierIds);
            goods.setUserIds(userIds);
        }


        //根据店铺名字模糊查询店铺
        if (StringUtils.isNotEmpty(goods.getStoreName())) {
            List<MallStore> mallStore = mallStoreService.selectStoreByName(goods.getStoreName());
            if (mallStore == null) {
                return new Page<>(mallGoods.getPageNum(), mallGoods.getPageSize());
            }
            ArrayList<Long> ids = new ArrayList<>();
            for (MallStore store : mallStore) {
                ids.add(store.getId());
//                log.info("ids的值：----{}",ids);
            }
            goods.setStoreIds(ids);

        }

        query = Wrappers.query(mallGoods);
        if (StringUtils.isNotEmpty(goods.getGoodsType())) {
            query.like("goods_type", goods.getGoodsType());
        }
        if (StringUtils.isNotEmpty(goods.getStoreType())) {
            query.like("store_type", goods.getStoreType());
        }
        if (StringUtils.isNotEmpty(goods.getOrderType())) {
            query.like("order_type", goods.getOrderType());
        }
        if (StringUtils.isNotEmpty(goods.getName())) {
            query.like("name", goods.getName());
        }
        if (goods.getCategory() != null) {
            query.eq("category_id", goods.getCategory());
        }
        if (goods.getChain() != null) {
            query.eq("chain", goods.getChain());
        }
        if (goods.getSupplier() != null) {
            query.eq("supplier", goods.getSupplier());
        }
        if (goods.getStore() != null) {
            query.eq("store", goods.getStore());
        }
        if (goods.getStartTime() != null && goods.getEndTime() != null) {
            query.between("create_time", goods.getStartTime(), goods.getEndTime());
        }
        if (goods.getMin() != null && goods.getMax() != null) {
            query.between("retail_price", goods.getMin(), goods.getMax());
        }
        if (StringUtils.isNotEmpty(goods.getStoreIds())) {
            query.in("store_id", goods.getStoreIds());
        }
        if (StringUtils.isNotEmpty(goods.getUserIds())) {
            query.in("user_id", goods.getUserIds());
        }
        if (StringUtils.isNotEmpty(goods.getSortStr()) && StringUtils.isNotEmpty(goods.getSortDesc())) {
            if ("descending".equals(goods.getSortDesc())) {
                query.orderByDesc(goods.getSortStr());
            } else {
                query.orderByAsc(goods.getSortStr());
            }
        } else {
            query.orderByDesc("top").orderByAsc("sort").orderByDesc("create_time");
        }

        query.eq("audit_status", 1);

        page = this.page(page, query);
        return page.convert(item -> {
            MallGoodTableVO vo = new MallGoodTableVO();


            LambdaQueryChainWrapper<MallCategory> mallCategoryLam = mallCategoryService.lambdaQuery();
            MallCategory mallCategory = mallCategoryLam.eq(MallCategory::getId, item.getCategoryId()).one();
            if (mallCategory != null) {
                vo.setTwoLevel(mallCategory.getName());
                mallCategory = mallCategoryService.lambdaQuery().eq(MallCategory::getId, mallCategory.getPid()).one();
                if (mallCategory != null) {
                    vo.setOneLevel(mallCategory.getName());
                }
            }
            if (null != item.getUserId()) {
                SysUser sysUser = sysUserService.selectUserById(item.getUserId());
                if (sysUser != null && sysUser.getNickName() != null) {
                    vo.setUserName(sysUser.getNickName());
                }
            }
            List<MallGoodsNorms> list = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getGoodsId, item.getId()).list();
            if (!list.isEmpty()) {
                if (item.getStore() != 1) {
                    long sum = list.stream().map(l -> l.getInventory()).collect(Collectors.toList()).stream().mapToLong(Long::longValue).sum();
                    item.setRetailPrice(list.get(0).getRetailPrice());
                    item.setSupplyPrice(list.get(0).getSupplyPrice());
                    item.setInventory(sum);
                    BeanUtils.copyProperties(item, vo);
                    vo.setDeductPrice(list.get(0).getDeductPrice());
                }
            }

            BeanUtils.copyProperties(item, vo);
            MallStore mallStore = mallStoreService.selectMallStoreById(item.getStoreId());
            if (mallStore != null) {
                vo.setStoreName(mallStore.getStoreName());
                vo.setStoreId(String.valueOf(mallStore.getId()));
            }
            return vo;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMallGoodsPo(MallGoodsAddDTO mallGoodsAddVO) {
        MallGoods goods = mallGoodsAddVO.getGoods();
        if (goods.getId() == null) {
            return 0;
        }
        if (mallGoodsAddVO.getNorms() == null) {
            throw new CustomException("规格信息不能为空");
        }
        if (mallGoodsAddVO.getUserId() != 1L && mallGoodsAddVO.getUserId() != 2L) {
            goods.setAuditStatus(0);
        }
        BigDecimal miniPrice = null;
        BigDecimal inventory = BigDecimal.ZERO;

//        MallGoodsNorms mallGoodsNorms = new MallGoodsNorms();
//        mallGoodsNorms.setGoodsId(goods.getId());
//
//        List<MallGoodsNorms> mallGoodsNormsList = mallGoodsNormsService.selectMallGoodsNormsList(mallGoodsNorms);
//        for (MallGoodsNorms goodsNorms : mallGoodsNormsList) {
//            mallGoodsNormsService.deleteMallGoodsNormsById(new ReqIdParam(goodsNorms.getId()));
//        }

        List<MallGoodsNorms> norms = mallGoodsAddVO.getNorms();

        for (MallGoodsNorms goodsNorms : norms) {
            if (goods.getStore() != null && goods.getStore() != 1) {
                inventory = inventory.add(BigDecimal.valueOf(goodsNorms.getInventory()));
                if (miniPrice == null) {
                    miniPrice = goodsNorms.getRetailPrice();
                    goods.setSupplyPrice(goodsNorms.getSupplyPrice());
                    goods.setDeductPrice(goodsNorms.getDeductPrice());
                }
                if (miniPrice.compareTo(goodsNorms.getRetailPrice()) > 0) {
                    miniPrice = goodsNorms.getRetailPrice();
                    goods.setSupplyPrice(goodsNorms.getSupplyPrice());
                    goods.setDeductPrice(goodsNorms.getDeductPrice());
                }
                goods.setInventory(inventory.longValue());
            }
            goodsNorms.setGoodsId(goods.getId());
            goodsNorms.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        }
        if (null != miniPrice) {
            goods.setRetailPrice(miniPrice);
        }


        baseMapper.updateById(goods);
        mallGoodsNormsService.saveOrUpdateBatch(norms);

        return 1;
    }

    /**
     * 描述信息  搜索功能
     *
     * @Author yaoruiqi
     * @Date: 2023/10/09 05:04
     */
    @Override
    @Transactional
    public IPage<MallGoodsListVO> apiList(MallGoodsSearchDTO mallGoodsSearchPo) {
        IPage<MallGoods> mallGoodsIPage = new Page<>(mallGoodsSearchPo.getPageNum(), mallGoodsSearchPo.getPageSize());
        if (StringUtils.isEmpty(mallGoodsSearchPo.getDimensionality())) {
            mallGoodsSearchPo.setDimensionality("0");
        }
        if (StringUtils.isEmpty(mallGoodsSearchPo.getLongitude())) {
            mallGoodsSearchPo.setLongitude("0");
        }

        IPage<MallGoods> page = baseMapper.getApiList(mallGoodsSearchPo, mallGoodsIPage);


        return page.convert(item -> {
            MallGoodsListVO mallGoodsListVO = new MallGoodsListVO();
            mallGoodsListVO.setId(item.getId());
            mallGoodsListVO.setSubTitle(item.getBrief());
            mallGoodsListVO.setCoverImg(item.getPicUrl());
            mallGoodsListVO.setTitle(item.getName());
            mallGoodsListVO.setPrice(item.getRetailPrice());
            mallGoodsListVO.setExpectCommoditySales((item.getExpectCommoditySales() == null ? BigDecimal.ZERO : item.getExpectCommoditySales()).intValue());
            mallGoodsListVO.setCommoditySales((item.getCommoditySales() == null ? BigDecimal.ZERO : item.getCommoditySales()).intValue());
            mallGoodsListVO.setLogisticsId(item.getLogisticsId());
            mallGoodsListVO.setIsHot(item.getIsHot());
            mallGoodsListVO.setDescribe(item.getDescribe());
            mallGoodsListVO.setCounterPrice(item.getCounterPrice());
            mallGoodsListVO.setInventory(item.getInventory());
            mallGoodsListVO.setCountyName(item.getCountyName());
            mallGoodsListVO.setStoreId(item.getStoreId() == null ? 0L : item.getStoreId());
            mallGoodsListVO.setStoreImg(StringUtils.isNotEmpty(item.getStoreImg()) ? item.getStoreImg() : "");
            mallGoodsListVO.setStoreName(StringUtils.isNotEmpty(item.getStoreName()) ? item.getStoreName() : "");
            mallGoodsListVO.setSetmealNameId(item.getSetmealId() == null ? 0L : item.getSetmealId());
            mallGoodsListVO.setDistance(item.getDistance() == null ? BigDecimal.ZERO : item.getDistance());
            return mallGoodsListVO;
        });
    }

    @Override
    public ResGoodsDetailVO queryInfoByGoodsSn(ReqIdParam id, LoginUser loginUser) {
        Optional<MallGoods> mallGoods = this.lambdaQuery().eq(MallGoods::getId, id.getId()).oneOpt();
        ResGoodsDetailVO resGoodsDetail = new ResGoodsDetailVO();
        BeanUtils.copyProperties(mallGoods.orElse(new MallGoods()), resGoodsDetail);
        resGoodsDetail.setBought(mallGoods.map(MallGoods::getCommoditySales).orElse(0L));
        Optional<MallCollect> mallCollect = mallCollectService
                .lambdaQuery()
                .eq(MallCollect::getUserId, loginUser.getAccountLogin().getId())
                .oneOpt();
        resGoodsDetail.setCollect(mallCollect.isPresent());
        Integer evaluateCount = mallCommentService
                .lambdaQuery()
                .eq(MallComment::getGoodsId, resGoodsDetail.getId())
                .eq(MallComment::getType, 0)
                .count();
        resGoodsDetail.setEvaluate(evaluateCount);
        resGoodsDetail.setPostage("包邮");

        return resGoodsDetail;
    }

    /**
     * 描述信息  app查看商品
     *
     * @Author yaoruiqi
     * @Date: 2023/10/12 06:42
     */
    @Override
    public MallGoodsDetailsVO goodInfoById(ReqIdParam idParam) {
        MallGoodsDetailsVO vo = new MallGoodsDetailsVO();
        MallGoods one = lambdaQuery().eq(MallGoods::getId, idParam.getId()).one();
        BeanUtils.copyProperties(one, vo);
        if (one.getStoreId() != null) {
            MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getId, one.getStoreId()).one();

            if (mallStore != null) {
                vo.setStoreImg(mallStore.getPhoto());
                vo.setStoreName(mallStore.getStoreName());
                vo.setStoreId(mallStore.getId());
//            vo.setStoreType(mallStore.getClassify());
            }
        }

        if (StringUtils.isNotEmpty(one.getChainId())) {
            one = supplierChainGoods(one);
            if (one.getIsOnSale() == 0) {
                throw new CustomException("该商品已下架！");
            }
        }

        List<MallGoodsNorms> norms = mallGoodsNormsService.list(new QueryWrapper<MallGoodsNorms>().eq("goods_id", one.getId()).orderByAsc("retail_price"));
        vo.setNorms(norms);
        vo.setLogisticsId(one.getLogisticsId());
        //商品宣传图片列表
        List<String> imgList = new ArrayList<>();
        if (StringUtils.isNotEmpty(one.getVideoUrl())) {
            imgList.add(one.getVideoUrl());
        }
        List<String> gallery = JSONObject.parseObject(one.getGallery(), ArrayList.class);
        imgList.addAll(gallery);
        vo.setGallerys(imgList);
        //商品评论
        List<MallOrderGoods> orderGoods = mallOrderGoodsService.list(new QueryWrapper<MallOrderGoods>().eq("goods_sn", one.getGoodsSn()));
        List<MallComment> mallComments = new ArrayList<>();
        for (MallOrderGoods orderGood : orderGoods) {
            if (orderGood.getComment() > 0) {
                List<MallComment> comments = mallCommentService.list(new QueryWrapper<MallComment>().eq("order_sn", orderGood.getOrderSn()).eq("is_hide", 0));
                mallComments.addAll(comments);
            }
        }
        vo.setComments(mallComments);
        return vo;
    }

    @Override
    public HttpResult<List<MallGoods>> selectNewGoods(MallGoods mallGoods) {
        return HttpResult.ok(baseMapper.selectOrderList(mallGoods));
    }

    @Override
    public void audit(MallGoodsAuditDTO dto) {
        String key = "goods_audit_" + dto.getId();
        RLock lock = redissonClient.getLock(key);
        lock.lock();
        try {
            MallGoods mallGoods = getById(dto.getId());
            if (mallGoods == null || mallGoods.getAuditStatus() != 0) {
                throw new CustomException("该条数据已被审核或失效，请刷新后重试！");
            }
            // 审核通过
            if (dto.getStatus() == 1) {
                lambdaUpdate().eq(MallGoods::getId, dto.getId())
                        .set(MallGoods::getAuditStatus, 1)
                        .set(MallGoods::getAuditOpinion, dto.getAuditOpinion())
                        .set(MallGoods::getIsOnSale, 1)
                        .update();
            }
            // 驳回
            else {
                lambdaUpdate().eq(MallGoods::getId, dto.getId())
                        .set(MallGoods::getAuditStatus, 2)
                        .update();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<MallGoods> getByOrderSn(String orderSn) {
        return baseMapper.getByOrderSn(orderSn);
    }

    @Override
    public HashMap<String, BigDecimal> getGoodPrice(GoodsVO good) {
        return baseMapper.getGoodPrice(good.getGoodsId(), good.getNormsId());
    }

    @Override
    public List<Integer> queryCount(String orderType) {
        // 上架中数量
        Integer count = lambdaQuery().eq(MallGoods::getIsOnSale, 1).eq(MallGoods::getAuditStatus, 1)
                .eq(MallGoods::getGoodsType, orderType)
                .count();
        // 下架数量
        Integer lowerCount = lambdaQuery().eq(MallGoods::getIsOnSale, 0).eq(MallGoods::getAuditStatus, 1)
                .eq(MallGoods::getGoodsType, orderType)
                .count();
        // 总数量
        int totalCount = (count != null ? count : 0) + (lowerCount != null ? lowerCount : 0);

        List<Integer> counts = new ArrayList<>();
        counts.add(totalCount);
        counts.add(count);
        counts.add(lowerCount);

        return counts;
    }

    /****
     * 上升
     * @param mallGoods
     * @return
     */
    @Override
    public boolean reSortOrderReduce(MallGoods mallGoods) {
        MallGoods one = lambdaQuery().eq(MallGoods::getId, mallGoods.getId()).one();
        one.setSort(one.getSort() - 1);
        updateById(one);

        return true;
    }

    /****
     * 下降
     * @param mallGoods
     * @return
     */
    @Override
    public boolean reSortOrderPlus(MallGoods mallGoods) {
        MallGoods one = lambdaQuery().eq(MallGoods::getId, mallGoods.getId()).one();
        one.setSort(one.getSort() + 1);
        updateById(one);

        return true;
    }

    @Override
    public IPage<MallGoodsListVO> recommendList(MallGoodsSearchDTO mallGoodsSearchPo) {
        IPage<MallGoods> mallGoodsIPage = new Page<>(mallGoodsSearchPo.getPageNum(), mallGoodsSearchPo.getPageSize());
        if (StringUtils.isEmpty(mallGoodsSearchPo.getDimensionality())) {
            mallGoodsSearchPo.setDimensionality("0");
        }
        if (StringUtils.isEmpty(mallGoodsSearchPo.getLongitude())) {
            mallGoodsSearchPo.setLongitude("0");
        }

        IPage<MallGoods> page = baseMapper.recommendList(mallGoodsSearchPo, mallGoodsIPage);

        return page.convert(item -> {
            MallGoodsListVO mallGoodsListVO = new MallGoodsListVO();
            mallGoodsListVO.setId(item.getId());
            mallGoodsListVO.setSubTitle(item.getBrief());
            mallGoodsListVO.setCoverImg(item.getPicUrl());
            mallGoodsListVO.setTitle(item.getName());
            mallGoodsListVO.setPrice(item.getRetailPrice());
            mallGoodsListVO.setExpectCommoditySales((item.getExpectCommoditySales() == null ? BigDecimal.ZERO : item.getExpectCommoditySales()).intValue());
            mallGoodsListVO.setDescribe(item.getDescribe());
            mallGoodsListVO.setCounterPrice(item.getCounterPrice());
            mallGoodsListVO.setInventory(item.getInventory());
            mallGoodsListVO.setDistance(item.getDistance() == null ? BigDecimal.ZERO : item.getDistance());
            mallGoodsListVO.setStoreId(item.getStoreId() == null ? 0L : item.getStoreId());
            mallGoodsListVO.setCountyName(item.getCountyName());
            mallGoodsListVO.setStoreImg(StringUtils.isNotEmpty(item.getStoreImg()) ? item.getStoreImg() : "");
            mallGoodsListVO.setStoreName(StringUtils.isNotEmpty(item.getStoreName()) ? item.getStoreName() : "");
            return mallGoodsListVO;
        });
    }


    /**
     * 描述信息  查询该商品是否下架
     *
     * @Author yaoruiqi
     * @Date: 2023/12/27 10:34
     */
    private MallGoods supplierChainGoods(MallGoods mallGoods) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", mallGoods.getChainId());
        String details = supplyChainlist("http://open.hetungongying.cn/supply/open/product/queryProductInfoNotUser", map);
        if (StringUtils.isEmpty(details)) {
            //如果该商品获取的为空，将商品设置为下架
            mallGoods.setIsOnSale(0);
        } else {
            BigDecimal inventory = BigDecimal.ZERO;
            BigDecimal miniPrice = null;
            JSONObject data1 = JSONObject.parseObject(details);
            if (data1 == null) {
                mallGoods.setIsOnSale(0);
            } else {
                JSONObject detailsJson = data1.getJSONObject("data");
                if (detailsJson == null) {
                    mallGoods.setIsOnSale(0);
                } else {
                    int shelf = Integer.parseInt(detailsJson.getString("shelf"));
                    if (shelf == 0) {
                        mallGoods.setIsOnSale(shelf);
                        String image = detailsJson.getString("image");
                        mallGoods.setGallery(image);
                        mallGoods.setVideoUrl(detailsJson.getString("productVideo"));
                        mallGoods.setDetail(detailsJson.getString("detailHtml"));
                        mallGoods.setKeywords(detailsJson.getString("keywords"));
                        mallGoods.setLogisticsId(1L);
                        mallGoods.setAuditStatus(1);
                        mallGoods.setUserId(9L);
                        mallGoods.setUpdateTime(LocalDateTime.now());
                        mallGoods.updateById();

                        //获取商品规格,存入商品规格表
                        JSONArray norms = detailsJson.getJSONArray("skus");
                        if (norms.size() < 1) {
                            mallGoods.setIsOnSale(0);
                        }
                        for (Object norm : norms) {
                            MallGoodsNorms mallGoodsNorms = new MallGoodsNorms();
                            JSONObject normsJson = JSONObject.parseObject(norm.toString());
                            JSONArray specDataList = normsJson.getJSONArray("specDataList");
                            for (Object spec : specDataList) {
                                JSONObject specJson = JSONObject.parseObject(spec.toString());
                                mallGoodsNorms = new MallGoodsNorms();
                                mallGoodsNorms.setGoodsId(mallGoods.getId());
                                mallGoodsNorms.setPicUrl(normsJson.getString("picUrl"));
                                mallGoodsNorms.setSupplyPrice(new BigDecimal(normsJson.getInteger("tradePrice")));
                                mallGoodsNorms.setRetailPrice(mallGoodsNorms.getSupplyPrice().multiply(new BigDecimal(3)));
                                mallGoodsNorms.setInventory(Long.valueOf(normsJson.getInteger("stock")));
                                inventory = inventory.add(BigDecimal.valueOf(Long.valueOf(normsJson.getInteger("stock"))));
                                mallGoodsNorms.setSkuId(specJson.getString("specId"));
                                if (specJson.getString("value") != null) {
                                    mallGoodsNorms.setAttribute(specJson.getString("value"));
                                } else {
                                    mallGoodsNorms.setAttribute(specJson.getString("name"));
                                }
                                mallGoodsNorms.setUserId(9L);//供应链userid，正式环境是54


                                if (mallGoodsNorms.getRetailPrice() != null) {
                                    if (miniPrice == null) {
                                        miniPrice = mallGoodsNorms.getRetailPrice();
                                        mallGoods.setSupplyPrice(mallGoodsNorms.getSupplyPrice() == null ? BigDecimal.ZERO : mallGoodsNorms.getSupplyPrice());
                                    }
                                    if (miniPrice.compareTo(mallGoodsNorms.getRetailPrice()) > 0) {
                                        miniPrice = mallGoodsNorms.getRetailPrice();
                                        mallGoods.setSupplyPrice(mallGoodsNorms.getSupplyPrice() == null ? BigDecimal.ZERO : mallGoodsNorms.getSupplyPrice());
                                    }

                                }
                                MallGoodsNorms one1 = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getSkuId, mallGoodsNorms.getSkuId()).eq(MallGoodsNorms::getGoodsId, mallGoods.getId()).one();
                                if (one1 != null) {
//                                    log.info("进入规格修改---{}", mallGoodsNorms.getSkuId());
                                    mallGoodsNorms.setId(one1.getId());
                                    mallGoodsNorms.setUpdateTime(LocalDateTime.now());
                                    mallGoodsNorms.updateById();
                                } else {
                                    mallGoodsNorms.setCreateTime(LocalDateTime.now());
                                    mallGoodsNorms.insert();
                                }
                            }
                        }
                        mallGoods.setInventory(inventory.longValue());
                        mallGoods.setRetailPrice(miniPrice);
                        mallGoods.updateById();
                    }
                }
            }
        }

        return mallGoods;
    }


    //生成签名
    public static String generateSign(Map<String, Object> params, String keySecret) {
        params.remove("sign");
        params.put("keySecret", keySecret);
        JSONConfig jsonConfig = new JSONConfig();
        //对json排序
        jsonConfig.setNatureKeyComparator();
        cn.hutool.json.JSONObject json = new cn.hutool.json.JSONObject(params, jsonConfig);
        // 对字符串进行MD5签名
        String sign = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(json.toString().getBytes());
            sign = bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //去除keySecret
        params.remove("keySecret");
        return sign;
    }

    // 将byte数组转换成十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    //调用第三方获得数据
    private String supplyChainlist(String url, Map<String, Object> params) {
        Date date = new Date();
        long timestamp = date.getTime();
        params.put("keyId", "d96hv94s2ilaobqi");
        params.put("timeMillis", timestamp);
        params.put("sign", "");
        String sign = generateSign(params, "ad179e56a1h33vd5963426sa9216ia0l0ba1fobbba4q3ai2");
        params.put("sign", sign);
        return HttpUtils.sendPostV2(url, JSON.toJSONString(params));
    }
}
